<template>
  <div ref="target" class="chart"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, onUnmounted } from "vue";
import * as echarts from "echarts";

const props = defineProps({
  data: Array,
});

let chart: echarts.ECharts | null = null;
const target = ref<HTMLElement | null>(null);

const ChartInit = () => {
  if (!target.value) return;

  if (chart) {
    chart.dispose();
    chart = null;
  }

  const option = {
    tooltip: {
      trigger: "item",
    },
    legend: {
      top: "5%",
      left: "center",
    },
    series: [
      {
        name: "产品占比",
        type: "pie",
        radius: ["40%", "70%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          show: false,
          position: "center",
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 40,
            fontWeight: "bold",
          },
        },
        labelLine: {
          show: false,
        },
        data: props.data,
      },
    ],
  };

  try {
    chart = echarts.init(target.value);
    chart.setOption(option);
  } catch (error) {
    console.error("Error setting option:", error);
  }
};

const handleResize = () => {
  if (chart) {
    chart.resize();
  }
};

let resizeObserver: ResizeObserver | null = null;

onMounted(() => {
  ChartInit();
  resizeObserver = new ResizeObserver(handleResize);
  if (target.value) {
    resizeObserver.observe(target.value);
  }
});

onUnmounted(() => {
  if (resizeObserver && target.value) {
    resizeObserver.unobserve(target.value);
    resizeObserver.disconnect();
  }
  if (chart) {
    chart.dispose();
    chart = null;
  }
});

watch(() => props.data, ChartInit);
</script>

<style lang="less" scoped>
.chart {
  height: 300px;
  width: 100%;
  margin-right: 50px;
}
</style>